from urllib.parse import quote
from datetime import datetime
from administrative.models import VehicleInformation, VehicleUseStatus
from dateutil.parser import parse
url = '/media/issueFile/2022/02/15/2f08f04d634ceaf3d0f24378d956a278bcf9e436/关于xxx的决议_1.pdf'


# 编码中文链接
def encode_chinese_url(url,parse_to = 1):
    # parse_to 1:转换为pdf链接 2：不转换

    url_split_Li = url.split('/')
    if url_split_Li == []:
        url_split_Li = url.split('\\')
    if not url_split_Li:
        print('请传递正确的url链接')
        return url
    filename = url_split_Li[-1]
    if parse_to == 1:
        pdf_name = filename.replace('.docx', '.pdf').replace('.doc', '.pdf')
        new_url = '/'.join(url_split_Li[:-1]) + '/' + quote(pdf_name)
    else:
        new_url = '/'.join(url_split_Li[:-1]) + '/' + quote(filename)
    return new_url



# 更新车辆表中车辆使用状态
def parse_car_status():
    car_info_objs = VehicleInformation.objects.all()
    for car_obj in car_info_objs:
        number_status_li = []
        car_use_objs = VehicleUseStatus.objects.filter(car_license_plate=car_obj.car_license_plate)
        for car_use_boj in car_use_objs:
            one_dict = {}
            one_dict["start_time"] = str(car_use_boj.start_time) if car_use_boj.start_time else ''
            one_dict["end_time"] = str(car_use_boj.end_time) if car_use_boj.end_time else ''
            one_dict["create_time"] = str(car_use_boj.create_time).split('.')[0]
            if one_dict['start_time']:
                now_time = datetime.now().strftime("%Y-%m-%d %H:%M")
                start_time = parse(one_dict["start_time"])
                end_time = parse(one_dict["end_time"])
                now_time = parse(now_time)
                if start_time < now_time < end_time:
                    number_status_li.append('1')
                elif now_time < start_time:
                    number_status_li.append('2')
                elif now_time > end_time:
                    number_status_li.append('3')
                    continue

        if '1' in number_status_li:
            car_obj.car_status = '1'
        else:
            if '2' in number_status_li:
                car_obj.car_status = '2'
            else:
                car_obj.car_status = '0'
        car_obj.save()

if __name__ == '__main__':
    encode_chinese_url(url)